package com.chuangyang.fixboxmaster.ui.widgets.timepick;

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.ViewFlipper;


import com.chuangyang.fixboxmaster.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


public class SelectTimeDateView extends PopupWindow implements OnClickListener {

	private Activity mContext;
	private View mMenuView;
	private ViewFlipper viewfipper;
	private Button btn_submit, btn_cancel;
	private String dateAndTime;
	protected final PopupWindow window;
    private TextWheelAdapter dayTextAdapter,hourTextAdapter,minuteTextAdapter;
	private WheelView dayWV, hourWV,  minuteWV;
	private int mCurDay = 0, mCurHour = 0, mCurMin = 0;

    private ArrayList<TimePickerDay> mOneWeekDays; // 七天
    private ArrayList<String> mOneWeeks;
    private ArrayList<String> mOneDayHours; // 0 - 23
    private ArrayList<String> mOneHourMin; // 0 - 60 十分钟间隔

    private static final int DEFAULT_PULL_OFF_TIME = 0; //

    private TimePickerClick mOKBtnClickListener;

    private String mDate;

	public SelectTimeDateView(Activity context, String dateTime) {
		super(context);
		mContext = context;
		this.window = new PopupWindow(mContext);
		// this.age = "2012-09-25";
		//SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");/* HH:mm */
		//String strDate = df.format(new Date());
		if(dateTime==null || dateTime.length() == 0){
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");/* HH:mm */
			String strDate = df.format(new Date());
			dateTime = strDate;
		}
        mDate = dateTime;


        // 根据日期算出几月几号
		this.dateAndTime = dateTime.substring(0,10); // yyyy-MM-dd

        // UI初始化
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mMenuView = inflater.inflate(R.layout.view_timepick, null);
		viewfipper = new ViewFlipper(context);
		viewfipper.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        dayWV = (WheelView) mMenuView.findViewById(R.id.wv_day);
        hourWV = (WheelView) mMenuView.findViewById(R.id.wv_hour);
        minuteWV = (WheelView) mMenuView.findViewById(R.id.wv_minute);
		btn_submit = (Button) mMenuView.findViewById(R.id.submit);
		btn_cancel = (Button) mMenuView.findViewById(R.id.cancel);
		btn_submit.setOnClickListener(this);
		btn_cancel.setOnClickListener(this);

        // 数据初始化
        initData(context);
        dayWV.addChangingListener(mListener);
        hourWV.addChangingListener(mHourListener);
        updateView();
	}

    public void setmOKBtnClickListener(TimePickerClick listener){
        mOKBtnClickListener = listener;
    }

    private OnWheelChangedListener mListener = new OnWheelChangedListener() {
        public void onChanged(WheelView wheel, int oldValue, int newValue) {
            if (newValue <= 0)
            {
                mCurHour = Integer.parseInt(mDate.split(" ")[1].substring(0,2)) + DEFAULT_PULL_OFF_TIME;
                mCurMin = Integer.parseInt(mDate.split(":")[1]);

                if (mCurMin < 30)
                {
                    mCurMin = 1;
                }
                else
                {
                    mCurMin = 0;
                    mCurHour++;
                }
                if (mCurHour >= 24)
                {
                    mCurHour = 0;
                }
            }
            else
            {
                mCurHour = 0;
                mCurMin = 0;
            }
            initHour(mContext);
            initMinute(mContext);
        }
    };

    private OnWheelChangedListener mHourListener = new OnWheelChangedListener() {
        public void onChanged(WheelView wheel, int oldValue, int newValue) {
            if (dayWV.getCurrentItem() == 0 && hourWV.getCurrentItem() == 0)
            {
                mCurMin = Integer.parseInt(mDate.split(":")[1]);

                if (mCurMin < 30)
                {
                    mCurMin = 1;
                }
                else
                {
                    mCurMin = 0;
                }
            }
            else
            {
                mCurMin = 0;
            }
            initMinute(mContext);
        }
    };

    private ArrayList<String> getOneWeek(){
        ArrayList<String> result = new ArrayList<>();
        mOneWeekDays = getOneWeekDate(mDate);

        for (int i = 0; i < mOneWeekDays.size(); i++)
        {
            result.add(mOneWeekDays.get(i).display);
        }
        return result;
    }

    private void initDay(Context context){
        mOneWeeks = getOneWeek();
        dayTextAdapter = new DateTextAdapter(context,mOneWeeks,0);
        dayWV.setViewAdapter(dayTextAdapter);
        dayWV.setCurrentItem(mCurDay);
    }

    private ArrayList<String> getHours(){
        ArrayList<String> result = new ArrayList<>();
        for (int i= mCurHour; i<= 23;i++)
        {
            if (i < 10)
                result.add("0"+i);
            else
                result.add(""+i);
        }

        return  result;
    }

    private void initHour(Context context){
        mOneDayHours = getHours();
        hourTextAdapter = new DateTextAdapter(context,mOneDayHours,0);
        hourWV.setViewAdapter(hourTextAdapter);
        hourWV.setCurrentItem(0);
    }

    private ArrayList<String> getMinutes(){
        ArrayList<String> result = new ArrayList<>();

        if (mCurMin == 0)
        {
            result.add("00");
        }
        result.add("30");
        return  result;
    }

    private void initMinute(Context context){
        mOneHourMin = getMinutes();
        minuteTextAdapter = new DateTextAdapter(context,mOneHourMin,mCurMin);
        minuteWV.setViewAdapter(minuteTextAdapter);
        minuteWV.setCurrentItem(mCurMin);
    }

    private void initData(Context context){
        initDay(context);
        initHour(context);
        initMinute(context);
    }
    private void updateView(){
        viewfipper.addView(mMenuView);
        viewfipper.setFlipInterval(6000000);
        this.setContentView(viewfipper);
        this.setWidth(LayoutParams.MATCH_PARENT);
        this.setHeight(LayoutParams.WRAP_CONTENT);
        this.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0x00000000);
        this.setBackgroundDrawable(dw);
        this.update();
    }


    private ArrayList<TimePickerDay> getOneWeekDate(String date){

        boolean bHaveToday = true;
        mCurHour = Integer.parseInt(date.split(" ")[1].substring(0,2)) + DEFAULT_PULL_OFF_TIME;
        mCurMin = Integer.parseInt(date.split(":")[1]);

        if (mCurMin < 30)
        {
            mCurMin = 1;
        }
        else
        {
            mCurMin = 0;
            mCurHour++;
        }

        if (mCurHour >= 24)
        {
            mCurHour = 0;
            //mCurDay++;
            bHaveToday = false;
        }
        ArrayList<TimePickerDay> dates = new ArrayList<>();
        try{

            TimePickerDay day = null;
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy年MM月dd日EE");
            Date convertedDate = null;
            String convert = "";
            convertedDate = dateFormat1.parse(date);

            int cnt = 1;
            while(cnt <= 7){
                day = new TimePickerDay();
                convert = dateFormat2.format(convertedDate);
                if (cnt == 1)
                {
                    if (!bHaveToday)
                    {
                        cnt++;
                        continue;
                    }
                    day.display = "今天";
                }
                else if(cnt == 2)
                {
                    day.display = "明天";

                }
                else if(cnt == 3)
                {
                    day.display = "后天";

                }
                else
                {
                    int pos = convert.indexOf("年");
                    day.display = convert.substring(pos + 1);
                }

                day.date = convert;
                convertedDate.setTime(convertedDate.getTime() + 24*60*60*1000);

                dates.add(day);
                cnt++;
            }
            if (!bHaveToday)
            {
                convertedDate.setTime(convertedDate.getTime() + 24*60*60*1000);
                int pos = convert.indexOf("年");
                day.display = convert.substring(pos + 1);
                day.date = convert;
                dates.add(day);
            }

        }catch (Exception e){
        }
        return dates;
    }

	@Override
	public void showAtLocation(View parent, int gravity, int x, int y) {
		super.showAtLocation(parent, gravity, x, y);
		viewfipper.startFlipping();
		// 在指定位置弹出弹窗
		if (gravity == Gravity.BOTTOM) {
			window.setAnimationStyle(R.style.AnimationPreview);
			window.showAtLocation(parent, Gravity.BOTTOM, x, y);

		} else {
			window.showAtLocation(parent, Gravity.BOTTOM, x, y);
		}
	}



    /**
     * Adapter for text wheels. Highlights the current value.
     */
    private class DateTextAdapter extends TextWheelAdapter{
        // Index of current item
        int currentItem;
        // Index of item to be highlighted
        int currentValue;

        public DateTextAdapter(Context context, ArrayList<String> list,int current) {
            super(context, list);
            currentValue = current;
            setTextSize(18);
        }

        protected void configureTextView(TextView view) {
            super.configureTextView(view);
            view.setTypeface(Typeface.SANS_SERIF);
        }

        public CharSequence getItemText(int index) {
            currentItem = index;
            return super.getItemText(index);
        }
    }
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.cancel://取消
			break;
        case  R.id.submit:
            String result = getSelectDate();
            mOKBtnClickListener.onOKClickCallBack(result);
            break;
		default:
			break;
		}
		this.dismiss();
		Log.i("TAG", dateAndTime);
	}

    /**
     * 是否选择的时间在当前时间之前
     * @return
     */
    private boolean validateDate(){

        String strSellectDate = getSelectDate();
        Date sellectDate = null;
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sellectDate = df.parse(strSellectDate);
        } catch (ParseException e) {
            e.printStackTrace();
            return  false;
        }

        Date currentDate = new Date();
        if (sellectDate.getTime() < currentDate.getTime())
            return false;
        return true;
    }

    /**
     * yyyy-MM-dd HH:MM:SS
     * @return
     */
    private String getSelectDate(){
        String result = "";
        int dayIndex = dayWV.getCurrentItem();
        int hourIndex = hourWV.getCurrentItem();
        int minuteIndex = minuteWV.getCurrentItem();

        TimePickerDay dayPicker = mOneWeekDays.get(dayIndex);
        String hourPick = mOneDayHours.get(hourIndex);
        String minutePick = mOneHourMin.get(minuteIndex);

        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy年MM月dd日EE");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
        Date convertedDate = null;
        String convert = "";
        try {
            convertedDate = dateFormat1.parse(dayPicker.date);
            convert = dateFormat2.format(convertedDate);
        }
        catch (Exception e){

        }
        result = convert + " " + hourPick + ":" + minutePick + ":" + "00";
        return result;
    }

    public interface TimePickerClick{

        public void onOKClickCallBack(String date);
    }

    public String getFirstDate(){
        String result = "";
        TimePickerDay dayPicker = mOneWeekDays.get(0);
        String hourPick = mOneDayHours.get(0);
        String minutePick = mOneHourMin.get(0);
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy年MM月dd日EE");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
        Date convertedDate = null;
        String convert = "";
        try {
            convertedDate = dateFormat1.parse(dayPicker.date);
            convert = dateFormat2.format(convertedDate);
        }
        catch (Exception e){

        }
        result = convert + " " + hourPick + ":" + minutePick + ":" + "00";
        return result;
    }
}
